import { copyFileSync, existsSync, readFileSync, writeFileSync } from "fs";
import path from "path";
import { afterBuildFinish } from "../build-custom/BuildCustom";
import PackUtil from "../utils/PackUtil";
import { ChannelInfo } from "./PlatformConfig";
import { WechatGame } from "./WechatGame";

export class Bilibili extends WechatGame {
    public async afterBuildFinish() {

        let channelInfo: ChannelInfo = this.configData.platforms[this.curPackChannel];
        //不同cocos版本处理方法不同，具体根据官网来修改，这里暂只处理2.4的
        if (PackUtil.compareVersion(this.configData.engineVer, "2.4.0") >= 0) {
            //复制res/bilibili/blapp-adapter-cocos.js到根目录
            const filePath = "./blapp-adapter-cocos.js";
            if (!existsSync(path.join(this.outputPath, channelInfo.platform, "blapp-adapter-cocos.js"))) {
                copyFileSync(filePath, path.join(this.outputPath, channelInfo.platform, "blapp-adapter-cocos.js"));
            }

            //修改game.js
            //在require('adapter-min.js');下一行加入require('blapp-adapter-cocos.js');
            //在window.boot();下一行加入bl.launchSuccess();
            try {
                const gamejsPath = path.join(this.outputPath, channelInfo.platform, "game.js");

                // 读取文件内容
                let content = readFileSync(gamejsPath, 'utf8');

                // 定义要查找的行和要插入的行
                const targetLine = "require('adapter-min.js');";
                const insertLine = "require('blapp-adapter-cocos.js');";

                // 查找目标行的位置
                const lines = content.split('\n');

                const targetIndex = lines.findIndex(line => line.trim() === targetLine);
                if (targetIndex === -1) {
                    console.log('未找到目标行:', targetLine);
                } else {
                    // 在目标行后插入新行
                    lines.splice(targetIndex + 1, 0, insertLine);
                }

                const targetLine2 = "window.boot();";
                const insertLine2 = "bl.launchSuccess();";
                const targetIndex2 = lines.findIndex(line => line.trim() === targetLine2);
                if (targetIndex === -1) {
                    console.log('未找到目标行:', targetLine2);
                } else {
                    // 在目标行后插入新行
                    lines.splice(targetIndex2 + 1, 0, insertLine2);
                }


                // 重新组合内容
                content = lines.join('\n');
                // 写回文件
                writeFileSync(gamejsPath, content, 'utf8');

                const gamejsonPath = path.join(this.outputPath, channelInfo.platform, "game.json");
                // 读取文件内容
                let jsonContent = JSON.parse(readFileSync(gamejsonPath, 'utf8'));
                //@ts-ignore
                if (!jsonContent.appId) {
                    //@ts-ignore
                    jsonContent.appId = channelInfo.appid;
                }
                //@ts-ignore
                if (!jsonContent.version) {
                    //@ts-ignore
                    jsonContent.version = this.version;
                }
                writeFileSync(gamejsonPath, JSON.stringify(jsonContent), 'utf8');

                console.log('文件修改完成');
            } catch (error) {
                console.error('处理文件时出错:', error);
            }
        }

        let configPath = path.join(this.projectDir, "settings", "wechatgame.json");
        if (existsSync(configPath)) {
            let channelInfo: ChannelInfo = this.configData.platforms[this.curPackChannel];
            let remoteDir = PackUtil.compareVersion(this.configData.engineVer, "2.4.0") >= 0 ? "remote" : "res";
            let remotepath = path.join(this.outputPath, channelInfo.platform, remoteDir);
            if (existsSync(remotepath) && channelInfo.remoteDir != "") {
                console.log('upload cdn res start');
                let cdnrespath = channelInfo.remoteDir;
                PackUtil.mkdirSync(channelInfo.remoteDir);
                try {
                    PackUtil.pullCDNRes(cdnrespath);
                } catch (error) {
                    console.error(error)
                }
                PackUtil.moveFiles(remotepath, cdnrespath);
                PackUtil.uploadCDNRes(cdnrespath);
                console.log('upload cdn res finish');
            }

            //TODO 上传到渠道
        } else {
            throw Error("please pack first in editor");
        }

        return new Promise<void>((resolve, reject) => {
            afterBuildFinish({ platform: this }, () => {
                resolve();
            })
        });
    }
}